package com.chilly.jdbc;

import com.mysql.cj.jdbc.Driver;
import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * Created by Chilly Cui on 2020/9/22.
 */
public class Demo {

    @Test
    void jdbc() throws ClassNotFoundException, IOException, SQLException {

        Properties info = new Properties();
        info.load(new FileInputStream("src\\jdbc.properties"));
        //info.list(System.out);

        info.getProperty("");
        String url = info.getProperty("url");
        String user = info.getProperty("user");
        String password = info.getProperty("password");
        String driver = info.getProperty("driver");


        //反射的方式加载类
        Class.forName(driver);

        //2 获取连接
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println("连接成功");

        Statement st = conn.createStatement();
        conn.prepareStatement("sql");

        // 关闭连接
        st.close();
        conn.close();

    }

    @Test
    void jdbc2() throws SQLException {

        //1 加载驱动 不推荐
        //DriverManager.registerDriver(new Driver());

        //2 获取连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", "root");
        System.out.println("连接成功");

        //3 执行增删查改
        String sql = " select * from user ";

        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(sql);

        while (rs.next()) {
            System.out.println(rs.getString("name"));
        }

        // 关闭连接
        st.close();
        conn.close();

    }
}
